import { Sequelize } from 'sequelize-typescript';
import { dbLogger } from '../logger';
import config from '../config';
import path from 'path';

// 使用数据库配置
const sequelize = new Sequelize(
    config.db.db_name as string, 
    config.db.db_user as string, 
    config.db.db_password, 
    {
        host: config.db.db_host,
        port: config.db.db_port as unknown as number,
        //数据库类型
        dialect: 'mysql', 
        // 连接池设置
        pool: {
            max: 5, // 最大连接数
            idle: 30000,
            acquire: 60000
        },
        // sequelize日志打印调用自定义dbLogger写入logs/db.log文件
        logging: msg => dbLogger.info(msg),
        // orm会添加默认字段，此处配置可调整默认的数据库更改字段
        define: {
            timestamps: true,
            createdAt: 'created_at',
            updatedAt: 'updated_at',
            deletedAt: 'deleted_at',
        },
        dialectOptions: {
            charset: 'utf8mb4', // 字符集
        },
        // 模型映射,编译前加载ts,编译后加载js
        models: [path.join(__dirname, '..', 'model/**/*.ts'), path.join(__dirname, '..', 'model/**/*.js')]
    });

const db = async () => {
    try {
        await sequelize.authenticate();
        console.log('---数据库链接成功---');
    } catch (error) {
        console.error('---无法链接到数据库:', error);
    }
}

export default db